import { NavigateService } from './../../../service/navigate.service';
import { TableService } from './../../../service/table.service';
import { MdDialog, MdDialogRef, MdDialogConfig } from "@angular/material";
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

export class TableOperateService {
    static Current: TableOperateService = new TableOperateService();
    private tableOperateDialog: TableOperateDialog;
    dialogRef: MdDialogRef<TableOperateDialog>;
    config: MdDialogConfig = {
        disableClose: false,
        width: '100%',
        position: {
            top: '0',
            bottom: '0',
            left: '0',
            right: '0'
        }
    }
    Regist(tableOperateDialog: TableOperateDialog) {
        this.tableOperateDialog = tableOperateDialog;
    }


    /**
     * @param  {string} dialogType  trans或者merge（转台|并台）
     * @param  {} tableZoneList  台桌分类
     * @param  {} tableList   分类下台桌列表
     * @param  {} tableZoneId  当前选中的台桌分类id
     */
    open(dialog: MdDialog, dialogType, tableZoneList, tableList, tableZoneId, tableInfo) {
        this.dialogRef = dialog.open(TableOperateDialog, this.config);

        this.tableOperateDialog.dialogType = dialogType;
        this.tableOperateDialog.tableZoneList = tableZoneList;
        this.tableOperateDialog.tableList = tableList;
        this.tableOperateDialog.tableZoneId = tableZoneId;
        this.tableOperateDialog.tableInfo = tableInfo;
        for (let value of tableZoneList) {
            if (value.id == tableZoneId) {
                this.tableOperateDialog.currentTableZone = value;
                break;
            }
        }
        return new Promise((resolve, reject) => {
            this.dialogRef.afterClosed().subscribe((tableList) => {
                this.dialogRef = null;
                resolve(tableList);
            })
        });
    }
}

@Component({
    //moduleId: module.id,
    selector: 'div[table-operate]',
    template: `
        <md-dialog-content fxLayout="column" class="table-operate-content">
            <header tabindex="0" autofocus class="app-header noshrink">
                <span id="dialog-back-btn" class="i-arrow-back margin-l header-icon" (click)="cancel()"></span>
                <span fxFlex="100%" class="margin-l-xs">{{tableInfo.name}}{{dialogType=='trans'?' 转台':' 并台'}}</span>
                <div class="noshrink margin-r" fxLayout="row" fxLayoutAlign="start center" [mdMenuTriggerFor]="appMenu">
                    <span class="margin-r-s">{{currentTableZone.name | stringEllipsis}}</span>
                    <div class="triangle-icon-down"></div>
                </div>
            </header>
            <md-menu #appMenu="mdMenu">
                <button md-menu-item *ngFor="let item of tableZoneList" (click)="onTableZoneSelectChange(item)">{{item.name | stringEllipsis}}</button>
            </md-menu>
            <div fxFlex="100%" fxLayout="column">
                <div class="table-operate-tip">选择要{{dialogType=='trans'?'转到':'合并'}}的台桌</div>
                <div class="table-container v-scroll" fxLayout="row" fxLayoutWrap="wrap" *ngIf="tableList && tableList.length">
                    <div fxFlex="33.3%" fxFlex.gt-xs="25%" fxLayoutAlign="center center" *ngFor="let table of tableList;let index = index">
                        <div fxLayout="column" class="table-item text-xs" (click)="onSelectTable(table)" [ngClass]="{'table-open': table.selected}">
                            <div class="table-item-info" fxLayout="column" fxFlex="100%">
                                <span fxFlex="100%" class="table-name">{{table.name}}</span>
                            </div>
                            <div fxLayout="row" fxLayoutAlign="start center" class="table-item-data noshrink">
                                <span class="text-xs table-item-icon i-person"></span>
                                <span fxFlex="100%" *ngIf="table.tableParty && table.tableParty.status != 'closed' && table.masterOrder">{{table.masterOrder.extended.headCount ? table.masterOrder.extended.headCount : ''}}</span>
                                <span *ngIf="!table.tableParty || !table.tableParty.status || table.tableParty.status == 'closed'">{{table.capacity ? table.capacity : 0}}</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="text-center v-gap" *ngIf="!tableList || !tableList.length">
                    <span>没有台桌数据</span>
                </div>
            </div>
            <button class="color-white bgcolor-primary noshrink normal-btn text-m" md-button (click)="ok()">确定</button>
        </md-dialog-content>
    `,
    styleUrls: ['../tableDetail.component.scss']
})
export class TableOperateDialog implements OnInit {

    constructor(
        public dialogRef: MdDialogRef<TableOperateDialog>,
        private tableSvr: TableService,
        private navSvr: NavigateService
    ) {
        TableOperateService.Current.Regist(this);
    }

    tableInfo = <any>{};
    dialogType: string;
    tableZoneId;
    tableZoneList = [];
    tableList = [];
    currentTableZone = <any>{};
    isOpenTableZone = false;
    divBackDrop = document.createElement("div");
    @Output() onResult = new EventEmitter();

    @Output() tableZoneSelectChange = new EventEmitter();

    ngOnInit() {
        this.navSvr.registGoBack(() => {
            let backBtn = document.getElementById("dialog-back-btn");
            if (backBtn) {
                backBtn.click();
            }
        });
    }

    async onTableZoneSelectChange(evt) {
        // this.tableZoneId = evt.target.value;
        this.tableZoneId = evt.id;
        this.currentTableZone = evt;
        this.isOpenTableZone = false;
        this.divBackDrop.remove();
        this.divBackDrop.onclick = null;
        let tbs = await this.tableSvr.GetTableList({ tableZoneId: evt.id });
        let r = [];
        if (Array.isArray(tbs) && tbs.length) {
            let thisId = (<any>this.tableInfo).id;
            r = tbs.filter(tb => {
                return tb.id != thisId;
            });
        }
        this.updateTableList(r);
    }

    updateTableList(tableList) {
        if (this.dialogType == "trans") {
            tableList = tableList.filter(table => {
                return !table.tableParty || table.tableParty.status != 'opening';
            });
        } else if (this.dialogType == "merge") {
            tableList = tableList.filter(table => {
                return !table.tableParty || !table.tableParty.tableGroupId;
            });
        }
        this.tableList = tableList;
    }

    onOpenTableZone() {
        this.isOpenTableZone = true;
        this.divBackDrop.className = "back-drop";
        let bodyDom = document.getElementsByClassName("table-zone")[0];
        bodyDom.appendChild(this.divBackDrop);
        this.divBackDrop.onclick = this.closeTableZoneList.bind(this);
    }
    closeTableZoneList() {
        this.isOpenTableZone = false;
        this.divBackDrop.remove();
        this.divBackDrop.onclick = null;
    }
    onSelectTable(tableItem) {
        if (this.dialogType == "trans") {
            this.tableList.forEach(x => {
                delete x.selected;
            })
            tableItem.selected = true;
        } else {
            tableItem.selected = !tableItem.selected;
        }

    }

    ok() {
        this.dialogRef.close(this.tableList);
    }

    cancel() {
        this.dialogRef.close(null);
    }
}